%Histology Registration
%Align flat-mount tile-scanned images with widefield images of cranial windows

%%
% load in images
widefield = imread('217_WF.png');
histology = imread('a217_Histology.png');

%ensure that any rotation or cropping applied to the histology image
%has also been applied to the raw-data z stack inputs below

%%
%select matched coordinates
%once you have everything you need, just close this window and code will proceed
%generally 20-25 points is optimal for a good alignment
%you need to select by-pair (ie switch between images)
%cannot choose all coordinates in one image then move to other
%if points are not spread uniformly across image, will throw an error
[wfCoor,hisCoor] = cpselect(widefield,histology,'Wait',true);

%%
%local weighted mean transformation
%transform the flat-mount histology into widefield coordinates
tform_lwm = fitgeotrans(hisCoor, wfCoor, 'lwm',length(wfCoor));
Rfixed = imref2d(size(widefield));
hisRegister_lwm = imwarp(histology, tform_lwm,'OutputView',Rfixed);
imshowpair(widefield,hisRegister_lwm,'blend'); %will show a blended pair - manually check quality here

%%
%load tiff stack
zStack_C1 = loadTiffStack('a217_SMA_zStack.tif');

%%
%function call to transform 
zStack_tForm(zStack_C1,1,widefield,tform_lwm,Rfixed)

%%
%transform a given tif z-stack using user generated tform
function res = zStack_tForm(currStack,channel,wf,tform,rfix)
    
    his_sz = size(currStack);
    wf_sz = size(wf);
    tfStack = zeros(wf_sz(1),wf_sz(2),his_sz(3)); 
    for x = 1:his_sz(3)
        currSlice = currStack(:,:,x);
        tfSlice = imwarp(currSlice, tform,'OutputView',rfix);
        tfStack(:,:,x) = tfSlice; 
    end
    
    filename = append('217_tfZstack_C',int2str(channel),'.tif');
    writetiff(uint8(tfStack),filename);
    
    %generate a blend of a max projection of the channel and the widefield
    tfStack_mp = max(tfStack,[],3);
    fusedpair = imfuse(wf,tfStack_mp,'blend'); 
    filename2 = append('217_tfzMP_C',int2str(channel),'_blendWF.tif');
    writetiff(fusedpair,filename2);
end 
